{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "---\n",
    "\n",
    "### 练习题 1: 变量与数据类型操作\n",
    "\n",
    "**题目：**  \n",
    "编写一个程序，要求用户输入一个整数和一个浮点数，然后计算它们的和、差、积和商，并输出结果。确保程序能够处理用户输入的错误。\n",
    "\n",
    "**参考答案：**\n",
    "\n",
    "```python\n",
    "try:\n",
    "    # 获取用户输入\n",
    "    integer_value = int(input(\"请输入一个整数: \"))\n",
    "    float_value = float(input(\"请输入一个浮点数: \"))\n",
    "\n",
    "    # 计算和、差、积、商\n",
    "    sum_value = integer_value + float_value\n",
    "    difference = integer_value - float_value\n",
    "    product = integer_value * float_value\n",
    "    quotient = integer_value / float_value\n",
    "\n",
    "    # 输出结果\n",
    "    print(f\"和: {sum_value}\")\n",
    "    print(f\"差: {difference}\")\n",
    "    print(f\"积: {product}\")\n",
    "    print(f\"商: {quotient}\")\n",
    "\n",
    "except ValueError:\n",
    "    print(\"输入错误，请输入有效的整数和浮点数。\")\n",
    "except ZeroDivisionError:\n",
    "    print(\"除数不能为零。\")\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### 练习题 2: 列表与字典操作\n",
    "\n",
    "**题目：**  \n",
    "给定一个包含学生姓名及其分数的列表，请编写一个程序，将这些信息存储在字典中。然后通过循环遍历字典，输出每个学生的姓名及其对应的分数，并计算和输出平均分。\n",
    "\n",
    "**参考答案：**\n",
    "\n",
    "```python\n",
    "# 示例学生数据\n",
    "students_scores = {\"Alice\": 85, \"Bob\": 90, \"Charlie\": 78}\n",
    "\n",
    "# 计算总分和学生数量\n",
    "total_score = 0\n",
    "num_students = len(students_scores)\n",
    "\n",
    "# 遍历字典，输出学生成绩\n",
    "for student, score in students_scores.items():\n",
    "    print(f\"{student}的分数是: {score}\")\n",
    "    total_score += score\n",
    "\n",
    "# 计算并输出平均分\n",
    "average_score = total_score / num_students\n",
    "print(f\"平均分是: {average_score:.2f}\")\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### 练习题 3: 函数与模块操作\n",
    "\n",
    "**题目：**  \n",
    "编写一个函数`calculate_circle_area(radius)`，计算并返回圆的面积。要求用户输入圆的半径，通过调用该函数计算并输出面积。如果用户输入的半径不是有效的数字，程序应捕获并处理异常。\n",
    "\n",
    "**参考答案：**\n",
    "\n",
    "```python\n",
    "import math\n",
    "\n",
    "def calculate_circle_area(radius):\n",
    "    \"\"\"计算圆的面积\"\"\"\n",
    "    return math.pi * radius ** 2\n",
    "\n",
    "try:\n",
    "    # 获取用户输入\n",
    "    radius = float(input(\"请输入圆的半径: \"))\n",
    "    \n",
    "    # 计算面积\n",
    "    area = calculate_circle_area(radius)\n",
    "    \n",
    "    # 输出结果\n",
    "    print(f\"圆的面积是: {area:.2f}\")\n",
    "\n",
    "except ValueError:\n",
    "    print(\"输入错误，请输入有效的数字作为半径。\")\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### 练习题 4: 类与对象\n",
    "\n",
    "**题目：**  \n",
    "创建一个名为`BankAccount`的类，具有属性`owner`（账户所有者姓名）和`balance`（账户余额），并包含以下方法：\n",
    "- `deposit(amount)`：存款，将`amount`添加到余额中。\n",
    "- `withdraw(amount)`：取款，从余额中减去`amount`，如果余额不足则提示用户。\n",
    "\n",
    "创建一个`BankAccount`对象，进行一些存款和取款操作，并输出最终余额。\n",
    "\n",
    "**参考答案：**\n",
    "\n",
    "```python\n",
    "class BankAccount:\n",
    "    \"\"\"银行账户类\"\"\"\n",
    "    \n",
    "    def __init__(self, owner, balance=0):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "    \n",
    "    def deposit(self, amount):\n",
    "        \"\"\"存款\"\"\"\n",
    "        self.balance += amount\n",
    "        print(f\"{self.owner}存款{amount}元，当前余额: {self.balance}元\")\n",
    "    \n",
    "    def withdraw(self, amount):\n",
    "        \"\"\"取款\"\"\"\n",
    "        if amount > self.balance:\n",
    "            print(\"余额不足，取款失败。\")\n",
    "        else:\n",
    "            self.balance -= amount\n",
    "            print(f\"{self.owner}取款{amount}元，当前余额: {self.balance}元\")\n",
    "\n",
    "# 创建账户并操作\n",
    "account = BankAccount(\"Alice\", 1000)\n",
    "account.deposit(100)\n",
    "account.withdraw(500)\n",
    "account.withdraw(700)  # 尝试超额取款\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### 练习题 5: 异常处理与文件操作\n",
    "\n",
    "**题目：**  \n",
    "编写一个程序，要求用户输入一个文件名和一个字符串，程序将字符串写入指定文件中。如果文件不存在，程序应创建该文件。然后读取文件内容并输出，最后输出文件的行数。如果在操作文件时出现错误，程序应捕获并处理异常。\n",
    "\n",
    "**参考答案：**\n",
    "\n",
    "```python\n",
    "try:\n",
    "    # 获取用户输入\n",
    "    filename = input(\"请输入文件名: \")\n",
    "    content = input(\"请输入要写入的字符串: \")\n",
    "\n",
    "    # 写入文件\n",
    "    with open(filename, \"w\") as file:\n",
    "        file.write(content)\n",
    "    \n",
    "    # 读取文件内容并输出\n",
    "    with open(filename, \"r\") as file:\n",
    "        lines = file.readlines()\n",
    "        print(\"文件内容:\")\n",
    "        for line in lines:\n",
    "            print(line.strip())\n",
    "    \n",
    "    # 输出文件的行数\n",
    "    print(f\"文件包含的行数: {len(lines)}\")\n",
    "\n",
    "except IOError as e:\n",
    "    print(f\"文件操作出现错误: {e}\")\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### 练习题 6: 综合练习：银行账户管理系统\n",
    "\n",
    "**题目：**  \n",
    "结合之前练习的知识点，创建一个简单的银行账户管理系统。该系统应允许用户：\n",
    "1. 创建账户\n",
    "2. 存款\n",
    "3. 取款\n",
    "4. 查询余额\n",
    "\n",
    "使用字典存储多个账户，账户名作为键，`BankAccount`对象作为值。系统应通过循环提供菜单选项，让用户选择要执行的操作，并捕获用户输入的错误。\n",
    "\n",
    "**参考答案：**\n",
    "\n",
    "```python\n",
    "class BankAccount:\n",
    "    \"\"\"银行账户类\"\"\"\n",
    "    \n",
    "    def __init__(self, owner, balance=0):\n",
    "        self.owner = owner\n",
    "        self.balance = balance\n",
    "    \n",
    "    def deposit(self, amount):\n",
    "        \"\"\"存款\"\"\"\n",
    "        self.balance += amount\n",
    "        print(f\"{self.owner}存款{amount}元，当前余额: {self.balance}元\")\n",
    "    \n",
    "    def withdraw(self, amount):\n",
    "        \"\"\"取款\"\"\"\n",
    "        if amount > self.balance:\n",
    "            print(\"余额不足，取款失败。\")\n",
    "        else:\n",
    "            self.balance -= amount\n",
    "            print(f\"{self.owner}取款{amount}元，当前余额: {self.balance}元\")\n",
    "    \n",
    "    def check_balance(self):\n",
    "        \"\"\"查询余额\"\"\"\n",
    "        print(f\"{self.owner}的账户余额: {self.balance}元\")\n",
    "\n",
    "# 创建一个字典来存储账户\n",
    "accounts = {}\n",
    "\n",
    "while True:\n",
    "    print(\"\\n选择操作:\")\n",
    "    print(\"1. 创建账户\")\n",
    "    print(\"2. 存款\")\n",
    "    print(\"3. 取款\")\n",
    "    print(\"4. 查询余额\")\n",
    "    print(\"5. 退出\")\n",
    "    choice = input(\"选择: \")\n",
    "    \n",
    "    if choice == \"1\":\n",
    "        owner = input(\"输入账户名称: \")\n",
    "        initial_deposit = float(input(\"输入初始存款: \"))\n",
    "        accounts[owner] = BankAccount(owner, initial_deposit)\n",
    "        print(f\"账户{owner}创建成功，当前余额: {initial_deposit}元\")\n",
    "    \n",
    "    elif choice == \"2\":\n",
    "        owner = input(\"输入账户名称: \")\n",
    "        if owner in accounts:\n",
    "            deposit_amount = float(input(\"输入存款金额: \"))\n",
    "            accounts[owner].deposit(deposit_amount)\n",
    "        else:\n",
    "            print(\"账户不存在。\")\n",
    "    \n",
    "    elif choice == \"3\":\n",
    "        owner = input(\"输入账户名称: \")\n",
    "        if owner in accounts:\n",
    "            withdraw_amount = float(input(\"输入取款金额: \"))\n",
    "            accounts[owner].withdraw(withdraw_amount)\n",
    "        else:\n",
    "            print(\"账户不存在。\")\n",
    "    \n",
    "    elif choice == \"4\":\n",
    "        owner = input(\"输入账户名称: \")\n",
    "        if owner in accounts:\n",
    "            accounts[owner].check_balance()\n",
    "        else:\n",
    "            print(\"账户不存在。\")\n",
    "    \n",
    "    elif choice == \"5\":\n",
    "        print(\"系统已退出。\")\n",
    "        break\n",
    "    \n",
    "    else:\n",
    "        print(\"无效选择，请重试。\")\n",
    "```\n",
    "\n",
    "---\n",
    "\n"
   ],
   "id": "f90c3b36a08bc2d1"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-09-01T17:28:49.702974Z",
     "start_time": "2024-09-01T17:28:49.697794Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "513d0d9f6c5689b0",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "4a770263316f81cd"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
